/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-05-22
 * Time: 14:37
 */
class Solution7 {
    public int coinChange(int[] coins, int amount) {
        int n = coins.length;

        int[][] dp = new int[n+1][amount+1];
        int INF = 0x3f3f3f3f;
        for(int j = 1 ; j <= amount; j++) {
            dp[0][j] = INF;
        }

        for(int i = 1; i <= n; i++) {
            for(int j = 0; j <= amount; j++) {
                dp[i][j] = dp[i-1][j];
                if(j >= coins[i-1]) {
                    dp[i][j] = Math.min(dp[i][j],dp[i][j-coins[i-1]]+1);
                }
            }
        }
        return dp[n][amount] >= INF ? -1 : dp[n][amount];
    }
}

//优化后
//class Solution7 {
//    public int coinChange(int[] coins, int amount) {
//        int n = coins.length;
//
//        int[] dp = new int[amount+1];
//        int INF = 0x3f3f3f3f;
//        for(int j = 1 ; j <= amount; j++) {
//            dp[j] = INF;
//        }
//
//        for(int i = 1; i <= n; i++) {
//            for(int j = coins[i-1]; j <= amount; j++) {
//                dp[j] = Math.min(dp[j],dp[j-coins[i-1]]+1);
//            }
//        }
//        return dp[amount] >= INF ? -1 : dp[amount];
//    }
//}